<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>排序算法</title>
</head>

<body>
  <script>
    function ArrayList() {
      this.array = []

      ArrayList.prototype.insert = function(el) {
        return this.array.push(el)
      }

      ArrayList.prototype.tostring = function(el) {
        return this.array.join('-')
      }

      ArrayList.prototype.bubblesort = function() {
        const length = this.array.length

        for (var j = length - 1; j >= 0; j--) {
          for (var i = 0; i < j; i++) {
            if (this.array[i] > this.array[i + 1]) {
              var temp = this.array[i]
              this.array[i] = this.array[i + 1]
              this.array[i + 1] = temp
            }
          }
        }
      }

      // 选择排序
      ArrayList.prototype.selectionsort = function() {
        const length = this.array.length

        for (var j = 0; j < length - 1; j++) {
          let max = 0 // 记录最大数字的下标, 默认是第一个

          for (var i = 1; i < length - j; i++) {
            if (this.array[max] < this.array[i]) {
              max = i
            }
          }
          let temp = this.array[max]
          this.array[max] = this.array[length - 1 - j]
          this.array[length - 1 - j] = temp
        }
      }
    }

    const arr = new ArrayList()
    arr.insert(10)
    arr.insert(12)
    arr.insert(14)
    arr.insert(1)
    arr.insert(30)
    arr.insert(150)
    arr.insert(12)
    // arr.bubblesort()
    arr.selectionsort()
    console.log(arr.tostring())
  </script>
</body>

</html>